//
//  SystemInfoViewController.m
//  SportSocial
//
//  Created by yull on 15/1/28.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "SystemInfoViewController.h"
#import "RecentSystemCell.h"
#import "ChatSysInfoDao.h"
#import "FriendNet.h"
#import "GroupNet.h"
#import "ChatInfoDao.h"

@interface SystemInfoViewController ()  <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *systemTableView;
@property (nonatomic, strong) NSMutableArray *systemArray;
@end

@implementation SystemInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"系统消息";
    [self addCommonBackButton];
    
    [self initSubViews];
    
    [self loadDataFromDB];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDataFromDB) name:@"ChatSystemInfoReload" object:nil];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.systemTableView.delegate = nil;
    self.systemTableView.dataSource = nil;
}

- (void)initSubViews
{
//    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height-49-64);
    
    if (MORE_THAN_IOS7) {
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    
    self.systemTableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.systemTableView.autoresizingMask = self.view.autoresizingMask;
    self.systemTableView.backgroundColor = [UIColor clearColor];
    self.systemTableView.delegate = self;
    self.systemTableView.dataSource = self;
    self.systemTableView.separatorInset = UIEdgeInsetsMake(0, 70, 0, 0);
    self.systemTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.systemTableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.systemArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatSystemInfo *recent = [self.systemArray objectAtIndex:indexPath.row];
    return [RecentSystemCell calculateCellHeightWithText:recent];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatSystemInfo *recent = [self.systemArray objectAtIndex:indexPath.row];
    
    static NSString *systemIdentifier = @"RecentSystemCell";
    RecentSystemCell *recentCell = [tableView dequeueReusableCellWithIdentifier:systemIdentifier];
    if (!recentCell) {
        recentCell = [[RecentSystemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:systemIdentifier];
        [recentCell.refuseButton addTarget:self action:@selector(onRefuseAction:withEvent:) forControlEvents:UIControlEventTouchUpInside];
        [recentCell.agreeButton addTarget:self action:@selector(onAgreeAction:withEvent:) forControlEvents:UIControlEventTouchUpInside];
    }
    [recentCell drawCellWithInfo:recent];
    
    return recentCell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChatSystemInfo *chatInfo = [self.systemArray objectAtIndex:indexPath.row];
    BOOL ret = [[ChatSysInfoDao shareInstance] deleteSystemInfo:chatInfo];
    
    if (ret) {
        [self.systemArray removeObject:chatInfo];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChatInfoReload" object:nil];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        });
    }
}

- (void)loadDataFromDB
{
    if (!self.systemArray) {
        self.systemArray = [NSMutableArray array];
    }else {
        [self.systemArray removeAllObjects];
    }
    
    [self.systemArray addObjectsFromArray:[[ChatSysInfoDao shareInstance] selectAlChatInfo]];
    
    @weakify(self);
    dispatch_async(dispatch_get_main_queue(), ^{
        @strongify(self);
        [self.systemTableView reloadData];
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Action
- (void)onRefuseAction:(id)sender withEvent:(UIEvent *)event
{
    NSSet *touchSet = [event allTouches];
    UITouch *touch = [touchSet anyObject];
    CGPoint point = [touch locationInView:self.systemTableView];
    NSIndexPath *indexPath = [self.systemTableView indexPathForRowAtPoint:point];
//    RecentSystemCell *cell = (RecentSystemCell *)[self.systemTableView cellForRowAtIndexPath:indexPath];
    
    ChatSystemInfo *chatInfo = [self.systemArray objectAtIndex:indexPath.row];
    
    if (chatInfo.infoType == SystemInfoTypeFriend) {

        [FriendNet refuseFriendWithUserId:chatInfo.userId key:chatInfo.key successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                chatInfo.friendType = SystemInfoFriendTypeNone;
                chatInfo.content = [[NSString alloc] initWithFormat:@"您拒绝了%@的好友请求",chatInfo.userName];
                
                [[ChatSysInfoDao shareInstance] updateChatInfo:chatInfo];
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [cell drawCellWithInfo:chatInfo];
                    [self.systemTableView reloadData];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }else {
        if (chatInfo.groupType == SystemInfoGroupTypeInvite) {

            [GroupNet refuseInviteWithGroupId:chatInfo.groupId key:chatInfo.key successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {

                BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                if (success) {
                    chatInfo.groupType = SystemInfoGroupTypeNone;
                    chatInfo.content = [[NSString alloc] initWithFormat:@"您拒绝了%@的邀请",chatInfo.userName];
                    
                    [[ChatSysInfoDao shareInstance] updateChatInfo:chatInfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [cell drawCellWithInfo:chatInfo];
                        [self.systemTableView reloadData];
                    });
                } else {
                    NSString *message = [responseObject objectForKey:@"message"];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showText:message time:2];
                    });
                }
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"网络连接失败" time:2];
                });
            }];
        }else if (chatInfo.groupType == SystemInfoFriendTypeApply) {

            [GroupNet refuseApplyWithGroupId:chatInfo.groupId userId:chatInfo.userId key:chatInfo.key successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {

                BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                if (success) {
                    chatInfo.groupType = SystemInfoGroupTypeNone;
                    chatInfo.content = [[NSString alloc] initWithFormat:@"您拒绝了%@的申请",chatInfo.userName];
                    
                    [[ChatSysInfoDao shareInstance] updateChatInfo:chatInfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [cell drawCellWithInfo:chatInfo];
                        [self.systemTableView reloadData];
                    });
                } else {
                    NSString *message = [responseObject objectForKey:@"message"];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showText:message time:2];
                    });
                }
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"网络连接失败" time:2];
                });
            }];
        }
    }
}

- (void)onAgreeAction:(id)sender withEvent:(UIEvent *)event
{
    NSSet *touchSet = [event allTouches];
    UITouch *touch = [touchSet anyObject];
    CGPoint point = [touch locationInView:self.systemTableView];
    NSIndexPath *indexPath = [self.systemTableView indexPathForRowAtPoint:point];
//    RecentSystemCell *cell = (RecentSystemCell *)[self.systemTableView cellForRowAtIndexPath:indexPath];
    
    ChatSystemInfo *chatInfo = [self.systemArray objectAtIndex:indexPath.row];
    
    if (chatInfo.infoType == SystemInfoTypeFriend) {

        [FriendNet agreeFriendWithUserId:chatInfo.userId key:chatInfo.key successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                chatInfo.friendType = SystemInfoFriendTypeNone;
                chatInfo.content = [[NSString alloc] initWithFormat:@"您同意了%@的好友申请",chatInfo.userName];
                
                [[ChatSysInfoDao shareInstance] updateChatInfo:chatInfo];
                dispatch_async(dispatch_get_main_queue(), ^{
//                    [cell drawCellWithInfo:chatInfo];
                    [self.systemTableView reloadData];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }else {
        if (chatInfo.groupType == SystemInfoGroupTypeInvite) {

            [GroupNet agreeInviteWithGroupId:chatInfo.groupId key:chatInfo.key successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {

                BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                if (success) {
                    chatInfo.groupType = SystemInfoGroupTypeNone;
                    chatInfo.content = [[NSString alloc] initWithFormat:@"您同意了%@的邀请",chatInfo.userName];
                    
                    [[ChatSysInfoDao shareInstance] updateChatInfo:chatInfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [cell drawCellWithInfo:chatInfo];
                        [self.systemTableView reloadData];
                    });
                } else {
                    NSString *message = [responseObject objectForKey:@"message"];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showText:message time:2];
                    });
                }
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"网络连接失败" time:2];
                });
            }];
        }else if (chatInfo.groupType == SystemInfoGroupTypeApply) {

            [GroupNet agreeApplyWithGroupId:chatInfo.groupId userId:chatInfo.userId key:chatInfo.key successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {

                BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                if (success) {
                    chatInfo.groupType = SystemInfoGroupTypeNone;
                    chatInfo.content = [[NSString alloc] initWithFormat:@"您同意了%@的申请",chatInfo.userName];
                    
                    [[ChatSysInfoDao shareInstance] updateChatInfo:chatInfo];
                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [cell drawCellWithInfo:chatInfo];
                        [self.systemTableView reloadData];
                    });
                } else {
                    NSString *message = [responseObject objectForKey:@"message"];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showText:message time:2];
                    });
                }
            } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"网络连接失败" time:2];
                });
            }];
        }
    }
}

@end
